﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Threading;

namespace LinkViewer.Controls
{
    /// <summary>
    /// Interaction logic for LinkItem.xaml
    /// </summary>
    public partial class LinkItem : UserControl
    {
        public LinkItem()
        {   
            try
            {
                InitializeComponent();
                //add our context menu back button to the browser
                ContextMenu menu = new System.Windows.Controls.ContextMenu();
                MenuItem backButton = new MenuItem();
                backButton.Header = "Back";
                MenuItem fwButton = new MenuItem();
                fwButton.Header = "Forward";
                fwButton.Click += delegate { try { chromeBrowser.GotoHistoryOffset(1); } catch { } };
                backButton.Click += delegate { try { chromeBrowser.GotoHistoryOffset(-1); } catch { } };
                menu.Items.Add(backButton);
                menu.Items.Add(fwButton);

                System.Windows.Forms.Timer checkSource = new System.Windows.Forms.Timer();
                checkSource.Interval = 3000;
                checkSource.Tick += new EventHandler(checkSource_Tick);
                checkSource.Start();
               
                //run these methods when the browser is ready to go
                chromeBrowser.Ready += delegate
                {
                    chromeBrowser.BeginLoading += delegate { loading.Visibility = Visibility.Visible; bReloadPage.Visibility = System.Windows.Visibility.Collapsed; bStopPage.Visibility = System.Windows.Visibility.Visible; };
                    chromeBrowser.FinishLoading += delegate { loading.Visibility = Visibility.Collapsed; bReloadPage.Visibility = System.Windows.Visibility.Visible; bStopPage.Visibility = System.Windows.Visibility.Collapsed; };
                    chromeBrowser.Height = LinkViewer.Properties.Settings.Default.BrowserSize;
                    chromeBrowser.KeyDown += new KeyEventHandler(chromeBrowser_KeyDown);
                    chromeBrowser.ContextMenu = menu;
                    chromeBrowser.MouseUp += new MouseButtonEventHandler(chromeBrowser_MouseUp);
                    zoomSlider.Value = 100;                    
                };
                DependencyPropertyDescriptor propDesc = DependencyPropertyDescriptor.FromProperty(LinkItem.LinkObjectProperty, typeof(LinkItem));
                propDesc.AddValueChanged(this, OnLinkObjectChanged);
            }
            catch (Exception x)
            {
                //MessageBox.Show("There was an error initializing a LinkView control.  Ensure you have all the required files.\n\n" + x.ToString());
                return;
            }
   
        }

        void checkSource_Tick(object sender, EventArgs e)
        {
            try
            {
                if (chromeBrowser.Source != LinkObject.URL)
                    lblWarning.Visibility = System.Windows.Visibility.Visible;
                else
                    lblWarning.Visibility = System.Windows.Visibility.Collapsed;
            }
            catch
            { }
        }
        public void SetHtml(string html)
        {
            chromeBrowser.LoadHtml(html);
        }
        void chromeBrowser_MouseUp(object sender, MouseButtonEventArgs e)
        {
            //for some reason needed to allow keyboard data to enter the browser window
            chromeBrowser.Focus();
        }

        void chromeBrowser_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyStates == KeyStates.Down)
            { 
            }
        }
       
        
        private void OnLinkObjectChanged(object sender, EventArgs e)
        {
            
            if (LinkObject != null)
            {
                tbNewTitle.Text = "";
                tbNewURL.Text = "";
                this.IsEnabled = true;
                if (LinkObject.Suspended)
                {
                    bSuspendLink.Visibility = System.Windows.Visibility.Collapsed;
                    bUnSuspendLink.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    bSuspendLink.Visibility = System.Windows.Visibility.Visible;
                    bUnSuspendLink.Visibility = System.Windows.Visibility.Collapsed;
                }


                if (LinkObject.Elevated)
                {
                    bElevateLink.Visibility = System.Windows.Visibility.Collapsed;
                    bUnElevateLink.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    bElevateLink.Visibility = System.Windows.Visibility.Visible;
                    bUnElevateLink.Visibility = System.Windows.Visibility.Collapsed;
                }

                //se tht etiel and url in case of a change
                lblCurrentTitle.Content = LinkObject.Title;
                lblCurrentURL.Content = LinkObject.URL;

                chromeBrowser.Navigate(LinkObject.URL);

                if (LinkObject.Page_ID > 0)
                {
                    //set the folder/page text
                    try
                    {
                        jcc.com.dailyez.Page page = jcc.StandardWebService.WebService.GetPage(jcc.StandardWebService.GetKey(), !LinkObject.Suspended ? LinkObject.Page_ID : jcc.StandardWebService.WebService.GetBadLink(jcc.StandardWebService.GetKey(), LinkObject.ID).Original_Page_ID);
                        string fPath = jcc.StandardWebService.WebService.GetFolderPath(jcc.StandardWebService.GetKey(), page.Folder_ID);
                        fPath += " / " + page.Title;
                        lblPageName.Content = fPath;
                    }
                    catch
                    { }
                }
            }
        }
        public int LinkID
        {
            get { return (int)GetValue(LinkIDProperty); }
            set { SetValue(LinkIDProperty, value); }
        }

        public ILink LinkObject
        {
            get { return (ILink)GetValue(LinkObjectProperty); }
            set { SetValue(LinkObjectProperty, value); }
        }
        
        public static readonly DependencyProperty LinkIDProperty = DependencyProperty.Register("LinkID", typeof(int), typeof(LinkItem));
        public static readonly DependencyProperty LinkObjectProperty = DependencyProperty.Register("LinkObject", typeof(ILink), typeof(LinkItem));

        private void bOpenContainerPage_Click(object sender, RoutedEventArgs e)
        {
            
            if (LinkObject.Page_ID > 0)
            {
                if (LinkObject.Suspended)
                {
                    jcc.com.dailyez.Bad_Links link = jcc.StandardWebService.WebService.GetBadLink(jcc.StandardWebService.GetKey(), LinkObject.ID);
                    if (link.Original_Page_ID > 0)
                    {
                        System.Diagnostics.Process.Start("http://www.metroeguide.net/Metro_eGuide/Default.aspx?DC=561&CC=" + link.Original_Page_ID);
                        return;
                    }
                }
                System.Diagnostics.Process.Start("http://www.metroeguide.net/Metro_eGuide/Default.aspx?DC=561&CC=" + LinkObject.Page_ID);
            }
            else
                MessageBox.Show("This link is not located on any Page");
        }

        private void bSaveItem_Click(object sender, RoutedEventArgs e)
        {
            if (jcc.Login.Level < 2)
            {
                MessageBox.Show("Your user account does not have permission to use this function");
                return;
            }
            int count = jcc.StandardWebService.WebService.GetLinkCount(jcc.StandardWebService.GetKey(), LinkObject.Title, LinkObject.URL);
            
            //if there is more than one occurance of the link
            if (count > 1)
            {
                
                if (count > 100)
                {
                    if (MessageBox.Show("There is a large amount of links the same as this one (" + count + ").  This operation will take some time, are you sure you want to continue?", "Large amount of links", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    {
                        return;
                    }
                }
                LaunchLoader();
                //create an instance of the ShowPagesDialog
                Controls.ShowPagesDialog sp = new ShowPagesDialog("There is " + count + " instances of this link, would you like to replace them all?\n\n" + //The message to display on the top
                                                                    "Note: If you replace all the links the controls will not be updated until an application restart.\n" +
                                                                    "You can restart the application by clicking the Restart application button on the top of the window.",
                                                                    jcc.StandardWebService.WebService.GetAllLinksByTitleAndURL(LinkObject.Title, LinkObject.URL), //Array of Links to display
                                                                    "Yes, replace them all", //The Yes Button Text
                                                                    "No, just replace this one" //The Cancel Button Text
                                                                    );
                KillLoader();

                if (sp.ShowDialog().HasValue)
                {
                    if (sp.DialogResult.Value)
                    {
                        string newTitle, newURL;
                        if (tbNewTitle.Text.Length > 1)
                            newTitle = tbNewTitle.Text;
                        else
                            newTitle = LinkObject.Title;
                        if (tbNewURL.Text.Length > 1)
                            newURL = tbNewURL.Text;
                        else
                            newURL = LinkObject.URL;


                        jcc.StandardWebService.WebService.ReplaceAllLink(jcc.StandardWebService.GetKey(), newTitle, newURL, LinkObject.Title, LinkObject.URL);

                        //log the vent
                        jcc.com.dailyez.Page page = jcc.StandardWebService.WebService.GetPage(jcc.StandardWebService.GetKey(), !LinkObject.Suspended ? LinkObject.Page_ID : jcc.StandardWebService.WebService.GetBadLink(jcc.StandardWebService.GetKey(), LinkObject.ID).Original_Page_ID);
                        jcc.StandardWebService.WebService.LogLinkViewerEvent(jcc.StandardWebService.GetKey(), DateTime.Now, jcc.Login.Username, page.Folder_ID, page.ID, LinkObject.ID, "{Date} - {Time} {Username} replaced " + count + " occurances of {URL:" + LinkObject.URL + ", Title:" + LinkObject.Title + "} with {URL:" + newURL + ", Title:" + newTitle + "} Orginally found in {Folder} / {Page}");


                        //update object for future uses
                        if (tbNewTitle.Text.Length > 1)
                        {
                            LinkObject.Title = tbNewTitle.Text;
                        }
                        if (tbNewURL.Text.Length > 1)
                        {
                            LinkObject.URL = tbNewURL.Text;
                        }

                        //set up the visuals
                        tbNewTitle.Text = "";
                        tbNewURL.Text = "";
                        lblCurrentTitle.Content = LinkObject.Title;
                        lblCurrentURL.Content = LinkObject.URL;
                    }
                    else
                    {
                        if (tbNewTitle.Text.Length > 1)
                        {
                            //log the vent
                            jcc.com.dailyez.Page page = jcc.StandardWebService.WebService.GetPage(jcc.StandardWebService.GetKey(), !LinkObject.Suspended ? LinkObject.Page_ID : jcc.StandardWebService.WebService.GetBadLink(jcc.StandardWebService.GetKey(), LinkObject.ID).Original_Page_ID);
                            jcc.StandardWebService.WebService.LogLinkViewerEvent(jcc.StandardWebService.GetKey(), DateTime.Now, jcc.Login.Username, page.Folder_ID, page.ID, LinkObject.ID, "{Date} - {Time} {Username} updated {Title:" + LinkObject.Title + "} with {Title:" + tbNewTitle.Text + "} in {Folder} / {Page}");
                            LinkObject.Title = tbNewTitle.Text;
                        }
                        if (tbNewURL.Text.Length > 1)
                        {
                            jcc.com.dailyez.Page page = jcc.StandardWebService.WebService.GetPage(jcc.StandardWebService.GetKey(), !LinkObject.Suspended ? LinkObject.Page_ID : jcc.StandardWebService.WebService.GetBadLink(jcc.StandardWebService.GetKey(), LinkObject.ID).Original_Page_ID);
                            jcc.StandardWebService.WebService.LogLinkViewerEvent(jcc.StandardWebService.GetKey(), DateTime.Now, jcc.Login.Username, page.Folder_ID, page.ID, LinkObject.ID, "{Date} - {Time} {Username} updated {URL:" + LinkObject.URL + "} with {URL:" + tbNewURL.Text + "} in {Folder} / {Page}");
                            LinkObject.URL = tbNewURL.Text;
                        }

                        DirectoryLink dirLinke = (DirectoryLink)LinkObject;
                        jcc.StandardWebService.WebService.UpdateLink(jcc.StandardWebService.GetKey(), LinkObject.ID, dirLinke.Link);
                        tbNewTitle.Text = "";
                        tbNewURL.Text = "";
                        lblCurrentTitle.Content = LinkObject.Title;
                        lblCurrentURL.Content = LinkObject.URL;
                    }
                }
                return;
            }

            //there was less than or equal to one occurance of the link
            if (tbNewTitle.Text.Length > 1)
            {
                //log the vent
                jcc.com.dailyez.Page page = jcc.StandardWebService.WebService.GetPage(jcc.StandardWebService.GetKey(), !LinkObject.Suspended ? LinkObject.Page_ID : jcc.StandardWebService.WebService.GetBadLink(jcc.StandardWebService.GetKey(), LinkObject.ID).Original_Page_ID);
                jcc.StandardWebService.WebService.LogLinkViewerEvent(jcc.StandardWebService.GetKey(), DateTime.Now, jcc.Login.Username, page.Folder_ID, page.ID, LinkObject.ID, "{Date} - {Time} {Username} updated {Title:" + LinkObject.Title + "} with {Title:" + tbNewTitle.Text + "} in {Folder} / {Page}");
                        
                LinkObject.Title = tbNewTitle.Text;
            }
            if (tbNewURL.Text.Length > 1)
            {
                jcc.com.dailyez.Page page = jcc.StandardWebService.WebService.GetPage(jcc.StandardWebService.GetKey(), !LinkObject.Suspended ? LinkObject.Page_ID : jcc.StandardWebService.WebService.GetBadLink(jcc.StandardWebService.GetKey(), LinkObject.ID).Original_Page_ID);
                jcc.StandardWebService.WebService.LogLinkViewerEvent(jcc.StandardWebService.GetKey(), DateTime.Now, jcc.Login.Username, page.Folder_ID, page.ID, LinkObject.ID, "{Date} - {Time} {Username} updated {URL:" + LinkObject.URL + "} with {URL:" + tbNewURL.Text + "} in {Folder} / {Page}");
                LinkObject.URL = tbNewURL.Text;
            }

            DirectoryLink dirLink = (DirectoryLink)LinkObject;
            jcc.StandardWebService.WebService.UpdateLink(jcc.StandardWebService.GetKey(), LinkObject.ID, dirLink.Link);
            tbNewTitle.Text = "";
            tbNewURL.Text = "";
            lblCurrentTitle.Content = LinkObject.Title;
            lblCurrentURL.Content = LinkObject.URL;
        }

        private void bCopyToCells_Click(object sender, RoutedEventArgs e)
        {
            tbNewURL.Text = (string)lblCurrentURL.Content;
            tbNewTitle.Text = (string)lblCurrentTitle.Content;
        }

        private void bUseCurrentPage_Click(object sender, RoutedEventArgs e)
        {
            tbNewURL.Text = chromeBrowser.Source;
        }

        private void bOpenInBrowser_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start((string)lblCurrentURL.Content);
            }
            catch
            { }
        }

        private void bSearch_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.google.com/#q=" + lblCurrentTitle.Content);
        }

        private void bReloadPage_Click(object sender, RoutedEventArgs e)
        {
            string url = (string)lblCurrentURL.Content;
            chromeBrowser.Source = url;
            chromeBrowser.Navigate(url);
        }

        private void bStopPage_Click(object sender, RoutedEventArgs e)
        {
            chromeBrowser.ExecuteJavascript("window.stop();", "");
        }

        #region Suspend and UnSuspend Internal Methods
        
        private void UnSuspendAllAndThis(ILink LinkObject, int count)
        {
            //Show loader
            LaunchLoader();

            jcc.com.dailyez.Bad_Links[] links = jcc.StandardWebService.WebService.GetBadLinksByTitleAndUrl(LinkObject.Title, LinkObject.URL);

            foreach (jcc.com.dailyez.Bad_Links l in links)
            {
                jcc.StandardWebService.WebService.UnSuspendLink(jcc.StandardWebService.GetKey(), l.Link_ID);
            }
            KillLoader();

            //log the vent
            jcc.com.dailyez.Page sPage = jcc.StandardWebService.WebService.GetPage(jcc.StandardWebService.GetKey(), !LinkObject.Suspended ? LinkObject.Page_ID : jcc.StandardWebService.WebService.GetBadLink(jcc.StandardWebService.GetKey(), LinkObject.ID).Original_Page_ID);
            jcc.StandardWebService.WebService.LogLinkViewerEvent(jcc.StandardWebService.GetKey(), DateTime.Now, jcc.Login.Username, sPage.Folder_ID, sPage.ID, LinkObject.ID, "{Date} - {Time} {Username} un-suspended " + count + " occurances of {URL:" + LinkObject.URL + ", Title:" + LinkObject.Title + "} initially found in {Folder} / {Page}");
            LinkObject.Suspended = false;
            bSuspendLink.Visibility = System.Windows.Visibility.Visible;
            bUnSuspendLink.Visibility = System.Windows.Visibility.Collapsed;
            bUnElevateLink.Visibility = System.Windows.Visibility.Collapsed;
            bElevateLink.Visibility = System.Windows.Visibility.Visible;
        }

        private void UnElevateAllAndThis(ILink LinkObject, int count)
        {

            //Show loader
            LaunchLoader();

            jcc.com.dailyez.Bad_Links[] links = jcc.StandardWebService.WebService.GetBadLinksByTitleAndUrl(LinkObject.Title, LinkObject.URL);

            foreach (jcc.com.dailyez.Bad_Links l in links)
            {
                jcc.StandardWebService.WebService.UnElevateLink(l.Link_ID);
            }
            KillLoader();

            //log the vent
            jcc.com.dailyez.Page sPage = jcc.StandardWebService.WebService.GetPage(jcc.StandardWebService.GetKey(), !LinkObject.Suspended ? LinkObject.Page_ID : jcc.StandardWebService.WebService.GetBadLink(jcc.StandardWebService.GetKey(), LinkObject.ID).Original_Page_ID);
            jcc.StandardWebService.WebService.LogLinkViewerEvent(jcc.StandardWebService.GetKey(), DateTime.Now, jcc.Login.Username, sPage.Folder_ID, sPage.ID, LinkObject.ID, "{Date} - {Time} {Username} un-elevated " + count + " occurances of {URL:" + LinkObject.URL + ", Title:" + LinkObject.Title + "} initially found in {Folder} / {Page}");
            LinkObject.Elevated = false;

            bUnElevateLink.Visibility = System.Windows.Visibility.Collapsed;
            bElevateLink.Visibility = System.Windows.Visibility.Visible;

        }
        private void ElevateAllAndThis(ILink LinkObject, int count)
        {
            LaunchLoader();

            jcc.com.dailyez.Link[] links = jcc.StandardWebService.WebService.GetAllLinksByTitleAndURL(LinkObject.Title, LinkObject.URL);
            foreach (jcc.com.dailyez.Link l in links)
            {
                jcc.StandardWebService.WebService.ElevateLink(l.ID);


            }
            
            KillLoader();

                //get the original page if suspended, otherwise just hte page
            jcc.com.dailyez.Page sPage = jcc.StandardWebService.WebService.GetPage(jcc.StandardWebService.GetKey(), !LinkObject.Suspended ? LinkObject.Page_ID : jcc.StandardWebService.WebService.GetBadLink(jcc.StandardWebService.GetKey(), LinkObject.ID).Original_Page_ID);
            jcc.StandardWebService.WebService.LogLinkViewerEvent(jcc.StandardWebService.GetKey(), DateTime.Now, jcc.Login.Username, sPage.Folder_ID, sPage.ID, LinkObject.ID, "{Date} - {Time} {Username} elevated " + count + " occurances of {URL:" + LinkObject.URL + ", Title:" + LinkObject.Title + "} initially found in {Folder} / {Page}");
            LinkObject.Elevated = true;
            LinkObject.Suspended = true;
            bSuspendLink.Visibility = System.Windows.Visibility.Collapsed;
            bUnSuspendLink.Visibility = System.Windows.Visibility.Visible;
            bElevateLink.Visibility = System.Windows.Visibility.Collapsed;
            bUnElevateLink.Visibility = System.Windows.Visibility.Visible;


        }
        private void SuspendAllAndThis(ILink LinkObject, int count)
        {
            //Show loader
            LaunchLoader();
            //Make a new web service call to suspend all link
            jcc.com.dailyez.Link[] links = jcc.StandardWebService.WebService.GetAllLinksByTitleAndURL(LinkObject.Title, LinkObject.URL);

            foreach (jcc.com.dailyez.Link l in links)
            {
                jcc.StandardWebService.WebService.SuspendLink(jcc.StandardWebService.GetKey(), l.ID);
            }
            KillLoader();
            //log the vent

            //get the original page if suspended, otherwise just hte page
            jcc.com.dailyez.Page sPage = jcc.StandardWebService.WebService.GetPage(jcc.StandardWebService.GetKey(), !LinkObject.Suspended ? LinkObject.Page_ID : jcc.StandardWebService.WebService.GetBadLink(jcc.StandardWebService.GetKey(), LinkObject.ID).Original_Page_ID);
            jcc.StandardWebService.WebService.LogLinkViewerEvent(jcc.StandardWebService.GetKey(), DateTime.Now, jcc.Login.Username, sPage.Folder_ID, sPage.ID, LinkObject.ID, "{Date} - {Time} {Username} suspended " + count + " occurances of {URL:" + LinkObject.URL + ", Title:" + LinkObject.Title + "} initially found in {Folder} / {Page}");
            LinkObject.Suspended = true;
            bSuspendLink.Visibility = System.Windows.Visibility.Collapsed;
            bUnSuspendLink.Visibility = System.Windows.Visibility.Visible;
        }
        private void SuspendThisLink()
        {
            //set the suspend to true
            LinkObject.Suspended = true;

            //set the buttons to correct states
            bSuspendLink.Visibility = System.Windows.Visibility.Collapsed;
            bUnSuspendLink.Visibility = System.Windows.Visibility.Visible;
            //log the event
            jcc.com.dailyez.Page page = jcc.StandardWebService.WebService.GetPage(jcc.StandardWebService.GetKey(), !LinkObject.Suspended ? LinkObject.Page_ID : jcc.StandardWebService.WebService.GetBadLink(jcc.StandardWebService.GetKey(), LinkObject.ID).Original_Page_ID);
            jcc.StandardWebService.WebService.LogLinkViewerEvent(jcc.StandardWebService.GetKey(), DateTime.Now, jcc.Login.Username, page.Folder_ID, page.ID, LinkObject.ID, "{Date} - {Time} {Username} suspended {ID:" + LinkObject.ID + ",URL:" + LinkObject.URL + ",Title:" + LinkObject.Title + "} in {Folder} / {Page}");
                   

        }
        private void UnSuspendThis()
        {
            
            bSuspendLink.Visibility = System.Windows.Visibility.Visible;
            bUnSuspendLink.Visibility = System.Windows.Visibility.Collapsed;
            bUnElevateLink.Visibility = System.Windows.Visibility.Collapsed;
            bElevateLink.Visibility = System.Windows.Visibility.Visible;
            jcc.com.dailyez.Page page = jcc.StandardWebService.WebService.GetPage(jcc.StandardWebService.GetKey(), !LinkObject.Suspended ? LinkObject.Page_ID : jcc.StandardWebService.WebService.GetBadLink(jcc.StandardWebService.GetKey(), LinkObject.ID).Original_Page_ID);
            //update the page so it opens the page the link is on instead of the page it started with
            LinkObject.Page_ID = page.ID;
            LinkObject.Suspended = false;
            jcc.StandardWebService.WebService.LogLinkViewerEvent(jcc.StandardWebService.GetKey(), DateTime.Now, jcc.Login.Username, page.Folder_ID, page.ID, LinkObject.ID, "{Date} - {Time} {Username} un-suspended {ID:" + LinkObject.ID + ",URL:" + LinkObject.URL + ",Title:" + LinkObject.Title + "} in {Folder} / {Page}");

        }
        #endregion

        private void bSuspendLink_Click(object sender, RoutedEventArgs e)
        {
            if (jcc.Login.Level < 2)
            {
                MessageBox.Show("Your user account does not have permission to use this function");
                return;
            }
            int count = jcc.StandardWebService.WebService.GetLinkCount(jcc.StandardWebService.GetKey(), LinkObject.Title, LinkObject.URL);
            
            //if there is more than one occurance of the link
            if (count > 1)
            {
                //create an instance of the ShowPagesDialog
                if (count > 100)
                {
                    if (MessageBox.Show("There is a large amount of links the same as this one (" + count + ").  This operation will take some time, are you sure you want to continue?", "Large amount of links", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    {
                        return;
                    }
                }
                LaunchLoader();
                Controls.ShowPagesDialog sp = new ShowPagesDialog("There is " + count + " instances of this link, would you like to suspend them all?\n\n" + //The message to display on the top
                                                                      "Note: If you suspend all the links the controls will not be updated until an application restart.\n" +
                                                                      "You can restart the application by clicking the Restart application button on the top of the window.",
                                                                      jcc.StandardWebService.WebService.GetAllLinksByTitleAndURL(LinkObject.Title, LinkObject.URL), //Array of Links to display
                                                                      "Yes, suspend them all", //The Yes Button Text
                                                                      "No, just suspend this one" //The Cancel Button Text
                                                                      );

                KillLoader();

                //show the dialog
                if (sp.ShowDialog().HasValue)
                {
                    //true if they clicked yes, false if they clicked no
                    if (sp.DialogResult.Value)
                    {
                        SuspendAllAndThis(LinkObject, count);
                        return;
                    }
                    //if false it will fall through and suspend just this one link
                }
            } // if (count > 1)
            
            SuspendThisLink();
                        
        }

        private void bUnSuspendLink_Click(object sender, RoutedEventArgs e)
        {
            if (jcc.Login.Level < 2)
            {
                MessageBox.Show("Your user account does not have permission to use this function");
                return;
            }

            jcc.com.dailyez.Bad_Links[] badLinks = jcc.StandardWebService.WebService.GetBadLinksByTitleAndUrl(LinkObject.Title, LinkObject.URL);

            //if there is more than one occurance of the link
            if (badLinks != null && badLinks.Length > 1)
            {
                //create an instance of the ShowPagesDialog
                if (badLinks.Length > 100)
                {
                    if (MessageBox.Show("There is a large amount of links the same as this one (" + badLinks.Length + ").  This operation will take some time, are you sure you want to continue?", "Large amount of links", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    {
                        return;
                    }
                }
                LaunchLoader();
                //create an instance of the ShowPagesDialog
                Controls.ShowPagesDialog sp = new ShowPagesDialog("There is " + badLinks.Length + " instances of this link, would you like to un-suspend them all?\n\n" + //The message to display on the top
                                                                    "Note: If you un-suspend all the links the controls will not be updated until an application restart.\n" +
                                                                    "You can restart the application by clicking the Restart application button on the top of the window.",
                                                                    jcc.StandardWebService.WebService.GetAllLinksByTitleAndURL(LinkObject.Title, LinkObject.URL), //Array of Links to display
                                                                    "Yes, un-suspend them all", //The Yes Button Text
                                                                    "No, just un-suspend this one" //The Cancel Button Text
                                                                    );
                KillLoader();

                //show the dialog
                if (sp.ShowDialog().HasValue)
                {
                    //true if they want to unsuspend all the links, false if they only want to suspend one
                    if (sp.DialogResult.Value)
                    {
                        UnSuspendAllAndThis(LinkObject, badLinks.Length);
                        return;
                    }

                    //if false, fall through and just handle it as if there was only one link
                }

            }// if (count > 1)

            UnSuspendThis();

         
        }

        private void bElevateLink_Click(object sender, RoutedEventArgs e)
        {
            if (jcc.Login.Level < 2)
            {
                MessageBox.Show("Your user account does not have permission to use this function");
                return;
            }

            int count = jcc.StandardWebService.WebService.GetLinkCount(jcc.StandardWebService.GetKey(), LinkObject.Title, LinkObject.URL);
            
            //if there is more than one occurance of the link
            if (count > 1)
            {
                //create an instance of the ShowPagesDialog
                if (count > 100)
                {
                    if (MessageBox.Show("There is a large amount of links the same as this one (" + count + ").  This operation will take some time, are you sure you want to continue?", "Large amount of links", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    {
                        return;
                    }
                }
                LaunchLoader();
                Controls.ShowPagesDialog sp = new ShowPagesDialog("There is " + count + " instances of this link, would you like to elevate them all?\n\n" + //The message to display on the top
                                                                      "Note: If you elevate all the links the controls will not be updated until an application restart.\n" +
                                                                      "You can restart the application by clicking the Restart application button on the top of the window.",
                                                                      jcc.StandardWebService.WebService.GetAllLinksByTitleAndURL(LinkObject.Title, LinkObject.URL), //Array of Links to display
                                                                      "Yes, elevate them all", //The Yes Button Text
                                                                      "No, just elevate this one" //The Cancel Button Text
                                                                      );
                KillLoader();

                //show the dialog
                if (sp.ShowDialog().HasValue)
                {
                    //true if they want to unsuspend all the links, false if they only want to suspend one
                    if (sp.DialogResult.Value)
                    {
                        ElevateAllAndThis(LinkObject, count);
                        return;
                    }

                    //if false, fall through and just handle it as if there was only one link
                }

            }// if (count > 1)

            LinkObject.Elevated = true;
            bElevateLink.Visibility = System.Windows.Visibility.Collapsed;
            bUnElevateLink.Visibility = System.Windows.Visibility.Visible;
            jcc.com.dailyez.Page page = jcc.StandardWebService.WebService.GetPage(jcc.StandardWebService.GetKey(), !LinkObject.Suspended ? LinkObject.Page_ID : jcc.StandardWebService.WebService.GetBadLink(jcc.StandardWebService.GetKey(), LinkObject.ID).Original_Page_ID);
            jcc.StandardWebService.WebService.LogLinkViewerEvent(jcc.StandardWebService.GetKey(), DateTime.Now, jcc.Login.Username, page.Folder_ID, page.ID, LinkObject.ID, "{Date} - {Time} {Username} elevated {ID:" + LinkObject.ID + ",URL:" + LinkObject.URL + ",Title:" + LinkObject.Title + "} in {Folder} / {Page}");
        }

        private void bUnElevateLink_Click(object sender, RoutedEventArgs e)
        {
            if (jcc.Login.Level < 2)
            {
                MessageBox.Show("Your user account does not have permission to use this function");
                return;
            }
            jcc.com.dailyez.Bad_Links[] badLinks = jcc.StandardWebService.WebService.GetBadLinksByTitleAndUrl(LinkObject.Title, LinkObject.URL);

            //if there is more than one occurance of the link
            if (badLinks != null && badLinks.Length > 1)
            {
                //create an instance of the ShowPagesDialog
                if (badLinks.Length > 100)
                {
                    if (MessageBox.Show("There is a large amount of links the same as this one (" + badLinks.Length + ").  This operation will take some time, are you sure you want to continue?", "Large amount of links", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    {
                        return;
                    }
                }
                LaunchLoader();
                //create an instance of the ShowPagesDialog
                Controls.ShowPagesDialog sp = new ShowPagesDialog("There is " + badLinks.Length + " instances of this link, would you like to un-elevate them all?\n\n" + //The message to display on the top
                                                                    "Note: If you un-suspend all the links the controls will not be updated until an application restart.\n" +
                                                                    "You can restart the application by clicking the Restart application button on the top of the window.",
                                                                    jcc.StandardWebService.WebService.GetAllLinksByTitleAndURL(LinkObject.Title, LinkObject.URL), //Array of Links to display
                                                                    "Yes, un-elevate them all", //The Yes Button Text
                                                                    "No, just un-elevate this one" //The Cancel Button Text
                                                                    );
                KillLoader();

                //show the dialog
                if (sp.ShowDialog().HasValue)
                {
                    //true if they want to unsuspend all the links, false if they only want to suspend one
                    if (sp.DialogResult.Value)
                    {
                        UnElevateAllAndThis(LinkObject, badLinks.Length);
                        return;
                    }

                    //if false, fall through and just handle it as if there was only one link
                }

            }// if (count > 1)

            LinkObject.Elevated = false;
            bElevateLink.Visibility = System.Windows.Visibility.Visible;
            bUnElevateLink.Visibility = System.Windows.Visibility.Collapsed;
            jcc.com.dailyez.Page page = jcc.StandardWebService.WebService.GetPage(jcc.StandardWebService.GetKey(), !LinkObject.Suspended ? LinkObject.Page_ID : jcc.StandardWebService.WebService.GetBadLink(jcc.StandardWebService.GetKey(), LinkObject.ID).Original_Page_ID);
            jcc.StandardWebService.WebService.LogLinkViewerEvent(jcc.StandardWebService.GetKey(), DateTime.Now, jcc.Login.Username, page.Folder_ID, page.ID, LinkObject.ID, "{Date} - {Time} {Username} de-elevated {ID:" + LinkObject.ID + ",URL:" + LinkObject.URL + ",Title:" + LinkObject.Title + "} in {Folder} / {Page}");

        }

        private void bDeleteLink_Click(object sender, RoutedEventArgs e)
        {
            if (jcc.Login.Level < 4)
            {
                MessageBox.Show("Your user account does not have permission to use this function");
                return;
            }

            int count = jcc.StandardWebService.WebService.GetLinkCount(jcc.StandardWebService.GetKey(), LinkObject.Title, LinkObject.URL);

            //if there is more than one occurance of the link
            if (count > 1)
            {
                //create an instance of the ShowPagesDialog
                if (count > 100)
                {
                    if (MessageBox.Show("There is a large amount of links the same as this one (" + count + ").  This operation will take some time, are you sure you want to continue?", "Large amount of links", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    {
                        return;
                    }
                }
                LaunchLoader();
                Controls.ShowPagesDialog sp = new ShowPagesDialog("There is " + count + " instances of this link, would you like to delete them all?\n\n" + //The message to display on the top
                                                                      "Note: If you suspend all the links the controls will not be updated until an application restart.\n" +
                                                                      "You can restart the application by clicking the Restart application button on the top of the window.",
                                                                      jcc.StandardWebService.WebService.GetAllLinksByTitleAndURL(LinkObject.Title, LinkObject.URL), //Array of Links to display
                                                                      "Yes, delete them all", //The Yes Button Text
                                                                      "No, just delete this one" //The Cancel Button Text
                                                                      );

                KillLoader();

                //show the dialog
                if (sp.ShowDialog().HasValue)
                {
                    //true if they clicked yes, false if they clicked no
                    if (sp.DialogResult.Value)
                    {
                        LaunchLoader();
                        jcc.com.dailyez.Link[] links = jcc.StandardWebService.WebService.GetAllLinksByTitleAndURL(LinkObject.Title, LinkObject.URL);
                        foreach (jcc.com.dailyez.Link l in links)
                            jcc.StandardWebService.WebService.DeleteLink(jcc.StandardWebService.GetKey(), l.ID);
                        KillLoader();
                        this.IsEnabled = false;
                        return;
                    }
                    //if false it will fall through and suspend just this one link
                }
            } // if (count > 1)

            if (MessageBox.Show("Do you really want to delete this link? This operation cannot be undone.", "Are you sure?", MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes)
            {
                jcc.com.dailyez.Page page = jcc.StandardWebService.WebService.GetPage(jcc.StandardWebService.GetKey(), !LinkObject.Suspended ? LinkObject.Page_ID : jcc.StandardWebService.WebService.GetBadLink(jcc.StandardWebService.GetKey(), LinkObject.ID).Original_Page_ID);
                jcc.StandardWebService.WebService.LogLinkViewerEvent(jcc.StandardWebService.GetKey(), DateTime.Now, jcc.Login.Username, page.Folder_ID, page.ID, LinkObject.ID, "{Date} - {Time} {Username} deleted {URL:" + LinkObject.URL + ", Title:" + LinkObject.Title + "} in {Folder} / {Page}");
                        
                LinkObject.Delete();
                this.IsEnabled = false;
            }

            //delete the link
        }

        private void root_SizeChanged(object sender, SizeChangedEventArgs e)
        {
          
        }

        private void root_Loaded(object sender, RoutedEventArgs e)
        {
            
        }

        private void chromeBrowser_Ready(object sender, EventArgs e)
        {
           // chromeBrowser.Width = yo.RenderSize.Width;
        }


        static Thread thread = null;
        public static void LaunchLoader()
        {
            thread = new Thread(new ThreadStart(CreateLoader));
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }
        public static void KillLoader()
        {
            try
            {
                thread.Abort();
            }
            catch
            { }
        }

        private static void CreateLoader()
        {
            JetNettEZEditor.Loading wpfWindow = new JetNettEZEditor.Loading();
            wpfWindow.Show();
            System.Windows.Threading.Dispatcher.Run();

        }

        private void bAddToWhiteList_Click(object sender, RoutedEventArgs e)
        {
            jcc.StandardWebService.WebService.AddURLToLinkCheckerWhitelist(LinkObject.URL);
            MessageBox.Show(LinkObject.URL + " has been added to the whitelist and will be automatically removed the first of next month");
        }

        private void bOpenInLPE_Click(object sender, RoutedEventArgs e)
        {

            string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Link Page Editor.exe";

            if (!System.IO.File.Exists(path))
            {
                MessageBox.Show("Cannot find Link Page Editor.  Looking in: " + path);
                return;
            }
      
            //...start it
            try
            {
                System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
                info.FileName = path;
                int originalPage = 0;
                if (LinkObject.Suspended)
                    originalPage = jcc.StandardWebService.WebService.GetBadLink(jcc.StandardWebService.GetKey(), LinkObject.ID).Original_Page_ID;
                else
                    originalPage = LinkObject.Page_ID;
                info.Arguments = jcc.Login.Username + " " + jcc.Login.Password + " " + originalPage;

                System.Diagnostics.Process.Start(info);
            }
            catch (Exception x)
            {
                MessageBox.Show("Error Starting the Link Page Editor\n" + x);
            }
        }

        private void zoomSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            try
            {
                chromeBrowser.SetZoom((int)zoomSlider.Value);
            }
            catch
            {
    
            }
        }

        private void Wikipedia_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://en.wikipedia.org/wiki/Special:Search/" + LinkObject.Title);
        }
    }
}
